#include <string>
#include <sstream>
#include "vl_cmd.h"
#include "env/vl_env.h"

using namespace VL;


/**
 * @Author: CimZzz
 * @Date: 2022-02-17 18:38:11
 * 
 * 执行命令行指令
 * 
 * @param cmd 命令行指令
 * @param echo 是否显示回响
 */
int CMDExecute::execute(std::string cmd, bool echo) {
	return CMDExecute::execute(cmd, nullptr, echo);
}



/**
 * @Author: CimZzz
 * @Date: 2022-02-17 18:38:11
 * 
 * 执行命令行指令
 * 
 * @param cmd 命令行指令
 * @param buffer 字节缓冲区
 * @param echo 是否显示回响
 */
int CMDExecute::execute(std::string cmd, Buffer* buffer, bool echo) {
	char line[1024];
	FILE* fp;
	if ((fp = popen((cmd).c_str(), "r")) == NULL) {
        return 1;
    }
    while (fgets(line, sizeof(line)-1, fp) != NULL){
		if(echo) {
			printf("%s", line);
		}
		if(buffer != nullptr) {
			buffer->appendStrBuffer(line);
		}
    }
	return pclose(fp);
}

/**
 * @Author: CimZzz
 * @Date: 2022-11-22 22:04:28
 * 
 * 获取进程错误信息
 * 
 * @param retCode 进程返回码
 * 
 * @return 进程错误信息
 */
std::string CMDExecute::getErrorMessage(int retCode) {
	if(retCode == 0) {
		return "";
	}
	if(WIFEXITED(retCode)) {
		std::stringstream ss;
		ss << WEXITSTATUS(retCode);
		return ss.str();
	}
	if(WIFSIGNALED(retCode)) {
		std::stringstream ss;
		ss << "Signaled " << WTERMSIG(retCode);
		ss << " Core dump " << WIFSIGNALED(retCode);
		return ss.str();
	}
	if(WSTOPSIG(retCode)) {
		std::stringstream ss;
		ss << "Stopped " << WIFSTOPPED(retCode);
		return ss.str();
	}
	return "unknown";
}